﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class panel_MasterPO : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        public panel_MasterPO()
        {
            InitializeComponent();
            mySetting = new INISettings();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            LoadData();
            this.MasterPO.DoubleClick += MasterPO_DoubleClick;
            this.MasterPO.PopupMenuShowing += MasterPO_PopupMenuShowing;
            this.masterPOContextMenu.ItemClicked += masterPOContextMenu_ItemClicked;
        }

        void masterPOContextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.masterPOContextMenu.Hide();            
            switch (e.ClickedItem.Name)
            {                
                case "addSelection":
                    frm_Add_MasterPO add_Form = new frm_Add_MasterPO();                    
                    add_Form.ShowDialog();
                    LoadData();
                    break;
                case "editSelection":
                    callEditForm();
                    break;
                case "cancelSelection":
                    cancelPO();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        void MasterPO_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.masterPOContextMenu.Show(MousePosition);
        }

        private void MasterPO_DoubleClick(object sender, EventArgs e)
        {
            callEditForm();
        }

        private void callEditForm()
        {
            DataRow row = MasterPO.GetFocusedDataRow();
            frm_Edit_MasterPO editForm = new frm_Edit_MasterPO();
            editForm.POID = row[0].ToString();
            if (editForm.LoadData())
            {
                editForm.ShowDialog();
                LoadData();
            }
            else
            {
                MessageBox.Show("Cannot edit selected record. Please try again.");
            }
        }

        //////////////////////////////////////////////////
        /// Load data from database to grid
        //////////////////////////////////////////////////
        private void LoadData()
        {
            DataSet sourceDataSet = new DataSet();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySetting.SQLConnectionString;
            string sql = "SELECT TOP 2000 t1.ID, t1.InputDate, t1.SupplierID, t2.SupplierName, t1.NameOfCommodity,"
                + " t3.DeliveryTermName, t4.PaymentName, t6.TransportName, t1.Remark, t1.Change, t1.Note, t1.Finished, t1.Paid,"
                + " t1.Cancelled, t5.ShipToName"
                + " FROM [241_MasterPO] AS t1 LEFT JOIN"
                + " [222_Supplier] AS t2 ON t1.SupplierID=t2.SupplierID LEFT JOIN"
                + " [222_DeliveryTerm] AS t3 ON t1.DeliveryTermID=t3.DeliveryTermID LEFT JOIN"
                + " [222_Payment] AS t4 ON t1.PaymentID=t4.PaymentID LEFT JOIN"
                + " [222_ShipTo] AS t5 ON t1.ShipToCode=t5.ShipToCode LEFT JOIN"
                + " [222_Transport] AS t6 ON t1.TransportID=t6.TransportID"
                + " ORDER BY SUBSTRING(t1.ID, 5, 6) DESC";            
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridMasterPO.DataSource = sourceDataSet.Tables[0];
            }
            else
            {
                DataTable newTable = new DataTable();
                newTable.Columns.Add("ID", typeof(string));
                newTable.Columns.Add("InputDate", typeof(DateTime));
                newTable.Columns.Add("SupplierID", typeof(string));
                newTable.Columns.Add("SupplierName", typeof(string));
                newTable.Columns.Add("NameOfCommodity", typeof(string));
                newTable.Columns.Add("DeliveryTermID", typeof(string));
                newTable.Columns.Add("PaymentID", typeof(string));
                newTable.Columns.Add("TransportID", typeof(string));
                newTable.Columns.Add("Remark", typeof(string));
                newTable.Columns.Add("Change", typeof(string));
                newTable.Columns.Add("Note", typeof(string));
                newTable.Columns.Add("Finished", typeof(string));
                newTable.Columns.Add("Paid", typeof(string));
                newTable.Columns.Add("Cancelled", typeof(string));
                newTable.Columns.Add("ShipToCode", typeof(string));
                gridMasterPO.DataSource = newTable;
            }
            MasterPO.Columns[0].Caption = "POID";
            MasterPO.Columns[1].Caption = "Input Date";
            MasterPO.Columns[2].Caption = "Supplier ID";
            MasterPO.Columns[3].Caption = "Supplier Name";
            MasterPO.Columns[4].Caption = "Name of Commodity";
            MasterPO.Columns[5].Caption = "Delivery Point";
            MasterPO.Columns[6].Caption = "Payment";
            MasterPO.Columns[7].Caption = "Transport";
            MasterPO.Columns[8].Caption = "Remark";
            MasterPO.Columns[9].Caption = "Change";
            MasterPO.Columns[10].Caption = "Note";
            MasterPO.Columns[11].Caption = "Finished";
            MasterPO.Columns[12].Caption = "Paid";
            MasterPO.Columns[13].Caption = "Cancelled";
            MasterPO.Columns[14].Caption = "ShipToCode";
            MasterPO.BestFitColumns();
        }

        ///////////////
        /// Cancel PO
        ///////////////
        private void cancelPO()
        {
            DataRow row = MasterPO.GetFocusedDataRow();
            string poid = row["ID"].ToString();
            if (MessageBox.Show("Really cancel?", "Confirm cancel", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (cancelAllOrderNo(poid))
                {
                    try
                    {
                        myConnection.Open();
                        SqlCommand cmd_sql = myConnection.CreateCommand();
                        cmd_sql.CommandText = "UPDATE [241_MasterPO] SET Cancelled=1"
                            + " WHERE ID='" + poid + "' AND Cancelled=0";
                        cmd_sql.ExecuteNonQuery();
                        cmd_sql.Dispose();
                        myConnection.Close();
                        MessageBox.Show("The POID " + poid + " has been canceled successfully.");
                    }
                    catch
                    {
                        if (myConnection.State == ConnectionState.Open)
                        {
                            myConnection.Close();
                        }
                        MessageBox.Show("Cannot cancel the POID " + poid + ". Please try again.");
                    }
                }
                else
                {
                    MessageBox.Show("Cannot cancel the POID " + poid + ". Please try again.");
                }
            }
        }
        

        ///////////////////////////////////////////
        /// Cancel all OrderNo for Master POID
        //////////////////////////////////////////
        private bool cancelAllOrderNo(string poid)
        {
            bool ret = true;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "UPDATE [241_MasterPODetails] SET Cancelled=1,"
                    + " WHERE POID='" + poid + "' AND Cancelled=0";
                cmd_sql.ExecuteNonQuery();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = false;
            }
            return ret;
        }

        private void poAdd_Click(object sender, EventArgs e)
        {
            frm_Add_MasterPO add_Form = new frm_Add_MasterPO();            
            add_Form.ShowDialog();
            LoadData();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void poUpdate_Click(object sender, EventArgs e)
        {
            callEditForm();
        }

        private void poCancel_Click(object sender, EventArgs e)
        {
            cancelPO();
        }
    }
}
